package com.thinkmore.es.test.bean;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.ArrayList;
import java.util.List;

public class EsUtil {

    private static List getDataResult(EsResult result, SearchResponse response, Class clazz) {
        List list = new ArrayList<>();
        SearchHits hits = response.getHits();
        SearchHit[] searchHits = hits.getHits();
        if (searchHits != null && searchHits.length > 0) {
            System.out.println("--------------------------------");
            for (SearchHit hit : hits.getHits()) {
                String json = hit.getSourceAsString();
                if (clazz != null) {
                    list.add(JSON.parseObject(json, clazz));
                } else {
                    list.add(json);
                }
            }
            result.setSortValues(searchHits[0].getSortValues());
            result.setResultSize(list.size());
        }
        return list;
    }

    public static EsResult ok(SearchParam searchParam, SearchResponse response) {
        EsResult result = new EsResult();
        result.setCode("200");
        result.setMsg("success");
        result.setPageSize(searchParam.getPageSize());
        result.setRequestId(searchParam.getRequestId());
        List dataResult = getDataResult(result, response, searchParam.getResultClass());
        result.setResult(dataResult);
        result.setScrollId(response.getScrollId());
        result.setTookTime(response.getTook().seconds());
        result.setTotalCount(response.getHits().getTotalHits().value);
        return result;
    }

    public static EsResult fail(SearchParam searchParam, String code, String msg) {
        EsResult result = new EsResult();
        result.setCode(code);
        result.setMsg(msg);
        result.setSearchParam(searchParam);
        if (searchParam != null) {
            result.setSearchParam(searchParam);
            result.setRequestId(searchParam.getRequestId());
        }
        return result;
    }
}
